from flask import redirect, request, url_for, render_template, session, jsonify, make_response
from . import wx_auth_blueprint as auth
import hashlib
from ..config.WXConfig import WxConfig
from ..WXUtil import get_wx_user
from flask_login import login_user, current_user
from .. import db
from ..models.tables import User, LoginCode
import json
import random
from ..utils.common import get_qr_code
import time
import uuid


@auth.route('/check')
def wx_check():
    data = request.args
    signature = data.get('signature')
    timestamp = data.get('timestamp')
    nonce = data.get('nonce')
    echostr = data.get('echostr')
    print('signature', signature)
    print('timestamp', timestamp)
    print('nonce', nonce)
    print('echostr', echostr)
    token = "elujiatoken111"  # 请按照公众平台官网\基本配置中信息填写
    # return echostr
    tmp_list = [token, timestamp, nonce]
    tmp_list.sort()
    tmp_str = tmp_list[0] + tmp_list[1] + tmp_list[2]
    sha1 = hashlib.sha1()
    sha1.update(tmp_str.encode('utf-8'))
    hashcode = sha1.hexdigest()
    print("handle/GET func: hashcode, signature: ", hashcode, signature)
    if hashcode == signature:
        return echostr
    else:
        return ''


@auth.route('/auth')
def wx_auth():
    code = request.args.get('code')
    ids = request.args.get('uuid')
    if not code:
        return '未接收到code'
    if not ids:
        return 'uuid 错误'
    else:
        wx_user = get_wx_user(code)
        login_code = LoginCode.query.filter_by(uuid=ids).first()
        if login_code is None:
            return '数据出错！未查到login_code'
        try:
            if wx_user and wx_user['openid']:
                if check_permission(wx_user):
                    login_code.openid = wx_user['openid']
                    login_code.status = 1
                    db.session.commit()
                    return render_template('code.html',login_code=login_code)
                else:
                    return '没有权限'
            return '授权失败，请重试'
        except Exception:
            return '授权失败，请重新扫码'


@auth.route('/confirm.do', methods=['POST'])
def confirm_auth():
    ids = request.form['uuid']
    openid = request.form['openid']
    login_code = LoginCode.query.filter_by(uuid=ids, openid=openid).first()
    if login_code is None:
        return jsonify({
            'state': -200,
            'msg': 'failed'
        })
    else:
        login_code.status = 2
        db.session.commit()
        return jsonify({
            'state': 200,
            'msg': 'success'
        })


@auth.route('/check_auth.do', methods=['GET'])
def check_auth():
    ids = request.args.get('uuid')
    login_code = LoginCode.query.filter_by(uuid=ids).first()
    if login_code is None:
        return jsonify({
            'state': 201,
            'msg': u'未查到login_code'
        })
    else:
        msg = ''
        if login_code.status == 2:
            user = User.query.filter_by(openid=login_code.openid).first()
            login_user(user, remember=False)
            msg = u'授权成功,跳转中...'
        elif login_code.status == 1:
            msg = u'扫码成功'
        else:
            msg = u'请扫码'

        return jsonify({
            'state': 200,
            'msg': msg,
            'status': login_code.status
        })


def check_permission(wx_user):
    user = User.query.filter_by(openid=wx_user['openid']).first()
    if user:
        return True
    return False


